<!DOCTYPE html>
<html lang="zh-en">
<head>
  <meta charset="UTF-8">
  <title>抽象提取公共组件类</title>
</head>
<body>
<!-- http://huziketang.mangojuice.top/books/react/lesson4 -->

<div class="wrap"></div>

<script>
  class Component {
    createDom(domString) { // 把字符串模板转化成 DOM元素
      let cDiv = document.createElement('div')
      cDiv.innerHTML = domString
      if (cDiv.children.length > 1) {
        throw new Error('组件需要在同一个元素中')
      }

      let dom = cDiv.children[0]
      document.body.appendChild(cDiv)
      document.body.removeChild(cDiv)

      return dom
    }
    setState(state) {
      let oldEl = this.el
      this.state = state
      this.el = this._renderDOM()
      if (this.onStateChange) {
        this.onStateChange(oldEl, this.el)
      }
    }
    _renderDOM() {
      this.el = this.createDom(this.render())
      if (this.onClick) {
        this.el.addEventListener('click', this.onClick.bind(this), false)
      }
      return this.el
    }
  }

  class LikeBtn extends Component{
    constructor() {
      super()
      this.state = {
        is_liked: false
      }
    }
    onClick() {
      this.setState({
        is_liked: !this.state.is_liked
      })
    }
    render() {
      return `
                <button class="btn">
                    <span class="btn-txt">${this.state.is_liked ? '取消' : '点赞'}</span>
                    <span>👍</span>
                </button>
              `
    }
  }

  const mount = (component, wrapper) => {
    wrapper.appendChild(component._renderDOM())
    component.onStateChange = (oldEl, newEl) => {
      wrapper.insertBefore(newEl, oldEl)
      wrapper.removeChild(oldEl)
    }
  }

  var eWrap = document.querySelector('.wrap')

  mount(new LikeBtn(), eWrap)
  mount(new LikeBtn(), eWrap)


</script>
</body>

</html>